﻿using System.Net.Http;
using System.Text;
using Serilog;

namespace ToolApp.Common
{
    public class HttpHelper
    {
        private static readonly HttpClient HttpClient = new();

        public static async Task<string?> GetAsync(string url)
        {
            try
            {
                using var response = await HttpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
                return null;
            }
        }

        public static async Task<string?> PostAsync(string url, string content)
        {
            try
            {
                using var response = await HttpClient.PostAsync(url, new StringContent(content, null, "application/json"));
                response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
                return null;
            }
        }

        public static async Task<string?> PutAsync(string url, string content)
        {
            try
            {
                using var response = await HttpClient.PutAsync(url, new StringContent(content));
                response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
                return null;
            }
        }

        public static async Task<string?> DeleteAsync(string url)
        {
            try
            {
                using var response = await HttpClient.DeleteAsync(url);
                response.EnsureSuccessStatusCode();
                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
                return null;
            }
        }
    }
}
